/*
 * ReplaceExpression.java
 *
 * Created on February 3, 2003, 4:21 PM
 */


import java.util.regex.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.lang.*;

/**
 *
 * @author  siewean
 */
public class ReplaceExpression {
    
    /** Creates a new instance of ReplaceExpression */
    public ReplaceExpression() {
    }
    
    public void fileReplace(String fileName, String toReplace, String replaceWith) throws IOException{
        // Compile regular expression
        Pattern pattern = Pattern.compile(toReplace);
        
        // Replace all occurrences of pattern in input
        Matcher matcher = pattern.matcher(getContents(fileName));
        String output = matcher.replaceAll(replaceWith);
        
        //System.out.println("output = " + output);
        FileWriter fw = new FileWriter(fileName);
        fw.write(output);
        fw.close();
        
    }
    
    public String getContents(String fileName) throws IOException{
        File f = new File(fileName);
        byte[] bytes = new byte[(int)f.length()];
        
        FileInputStream fis = new FileInputStream(f);
        fis.read(bytes);
        fis.close();
        return new String(bytes);
        
        
    }
    
}
